import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import CourseRecordListABI from "../contract/ABIs/CourseList.json"; // 课程记录列表合约 ABI
import AdminABI from '../contract/ABIs/Admin.json'; // 管理员合约 ABI
import * as XLSX from 'xlsx'; // 导入 XLSX 库用于解析 Excel 文件

import CourseRecordListAddress from "../contract/ADDRESSes/CourseListAddress.js" // 课程记录列表合约地址
import AdminNavBar from './nav/AdminNavBar.js'
import Head from './nav/Head.js';


const Admin_initMultiCourseRecord = () => {


    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractCourseRecordList, setcontractCourseRecordList] = useState(null);
    const [contractAdmin, setcontractAdmin] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);


    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建课程记录合约实例
                    const courseRecordListInstance = new web3Instance.eth.Contract(
                        CourseRecordListABI,
                        CourseRecordListAddress
                    );
                    setcontractCourseRecordList(courseRecordListInstance);

                    // 创建管理员合约实例
                    const adminInstance = new web3Instance.eth.Contract(
                        AdminABI,
                        address
                    );
                    setcontractAdmin(adminInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取管理员合约的 owner 地址
                    const ownerAddress = await adminInstance.methods.getOwner().call();
                    // 检查当前账户是否是管理员本人
                    setIsAdmin(currentAddress === ownerAddress);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);
    // 初始化多个用户的同一套课程结构
    // 确保在初始化状态时 userAddrslist 是一个数组
    const [courseNumbersList, setcourseNumbersList] = useState([]);
    const [userAddressesList, setuserAddressesList] = useState([]);
    const handleFileUpload = (e) => {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = (evt) => {
            const data = evt.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

            jsonData.slice(1).forEach(row => {
                const courseNumber = row[0]?.toString().trim(); // 获取并清理课程编号
                const userAddr = row[1]?.toString().trim(); // 获取并清理用户地址
                if (courseNumber) {//判断是否为空
                    courseNumbersList.push(courseNumber); // 如果课程编号非空，加入数组
                }
                if (userAddr) {
                    userAddressesList.push(userAddr); // 如果用户地址非空，加入数组
                }
            });
        };
        reader.readAsBinaryString(file);
    };

    // 初始化多个用户的同一套课程函数
    const AddStudents = async () => {
        if (contractCourseRecordList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("courseNumbersList:", courseNumbersList,);
                console.log("userAddressesList:", userAddressesList);
                // const courseNumbers = ["1111", "2222"];
                // const userAddrs = ["0x01B1557408B32e82E3292cAbDa217Ea79112e731"]
                // 调用智能合约的某个函数
                const result = await contractCourseRecordList.methods.addCourseToStudents(userAddressesList, courseNumbersList).send({ from: fromAddress });
                console.log("result:", result)
                // await contractCourseRecordList.methods.initMultiCourseRecord(courseNumbers, userAddrs).send({ from: fromAddress });
                alert("添加成功")
            } catch (error) {
                console.error(error);
                alert("添加失败")
            }
        }
    };


    return (
        <div>
            {/* 如果当前账户不是管理员，则显示提示信息 */}
            {!isAdmin && (<div>您没有权限访问此页面。</div>)}

            {/* 管理员界面 */}
            {isAdmin && (
                <div className="main-container" style={{
                    backgroundColor: '#FFFFFF'
                }}>
                    <AdminNavBar address={address}></AdminNavBar>

                    <div className="app-container">
                        <Head></Head>
                        <div className="app-body">
                            <main className="page hire-me-page">
                                <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                    data-bs-theme="light"
                                    style={{
                                        backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                    }}
                                >

                                    <h1>初始化多个用户的同一套课程记录</h1>
                                    <div class="mb-3">

                                        {/* 添加上传 Excel 文件的表单 */}
                                        <input type="file" accept=".xlsx, .xls" onChange={handleFileUpload} />




                                        <div className="mb-3 mt-4">
                                            <button className="btn btn-primary btn-lg d-block w-100" onClick={AddStudents}>添加</button>
                                        </div>



                                    </div>
                                </div>

                            </main>
                        </div>
                        <div className="app-footer">
                            <span>
                                © Bootstrap Gallery 2023
                            </span>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default Admin_initMultiCourseRecord;